/*
 * Test firmware Arduino in combination with XPORT
 *
 * My connections between Arduino-XPORT:
 *	# TX - pin3 - red
 * 	# RX - pin4 - blue
 *	# GND - white
 */
#include <avr/interrupt.h>
#include <avr/io.h>

#include <NewSoftSerial.h>

#define INIT_TIMER_COUNT 6
#define RESET_TIMER2 TCNT2 = INIT_TIMER_COUNT

#define DBG_MESSAGES

// One and two phases
// 60000ms / 48steps = 1250ms/step
#define TRACK  1250

enum HttpStatusEnum { HTTP_IDLE, HTTP_CONNECT, HTTP_WAIT_FOR_ACK, HTTP_TRANSFER, HTTP_DISCONNECTED, HTTP_ERROR };
enum HttpStatusEnum HttpStatus;

int ledPin = 13;    // LED connected to digital pin 9
volatile int tmp = 0;
int input = 0;
volatile int delayvalue = 500;
bool led_state = LOW;
int int_counter = 0;

char ReturnStr[256];
int  ReturnStrCounter;
int  string_start;

NewSoftSerial Xport(4 /*Rx*/,3 /*Tx*/);

// Aruino runs at 16 Mhz, so we have 1000 Overflows per second...
// 1/ ((16000000 / 64) / 256) = 1 / 1000
ISR(TIMER2_OVF_vect) {
  RESET_TIMER2;
  int_counter++;
  if(!(int_counter%TRACK))
  {
    led_state = not led_state;
    digitalWrite(ledPin, led_state);   // set the LED on/off
  }
};


// The setup() method runs once, when the sketch starts
void setup()   {                
  // initialize the digital pin as an output:
  pinMode(ledPin, OUTPUT);  
  Serial.begin(57600); 
 
  Xport.begin(1200);
  Xport.flush(); 
   
  //Timer2 Settings: Timer Prescaler /64,
  TCCR2A |= (1<<CS22);
  TCCR2A &= ~((1<<CS21) | (1<<CS20));
  // Use normal mode
  TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
  // Use internal clock - external clock not used in Arduino
  ASSR |= (0<<AS2);
  //Timer2 Overflow Interrupt Enable
  TIMSK2 |= (1<<TOIE2) | (0<<OCIE2A);
  RESET_TIMER2;
  sei();
  
  printMenu();

  ReturnStrCounter = 0;
  string_start = 0;

}

// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()                     
{

	switch(HttpStatus){
	case HTTP_IDLE:
		input = Serial.read();
		switch(input){
		case 't':
			Serial.print("t");
#ifdef DBG_MESSAGES
			Serial.print("\n\t ### Received char t -> going to HTTP_CONNECT");
#endif
			HttpStatus = HTTP_CONNECT;
			break;
		default:
			// do nothing and wait for a command
                        break;
		}
		break;
	case HTTP_CONNECT:
#ifdef DBG_MESSAGES
		Serial.print("\n\t ### Send the command for connection (C67.220.217.230/80) -> going to HTTP_WAIT_FOR_ACK");
#endif
		Xport.print("C67.220.217.230/80\n");
		HttpStatus = HTTP_WAIT_FOR_ACK;
		break;
	case HTTP_WAIT_FOR_ACK:
		if(Xport.available()){
			if( (char)Xport.read() == 'C'){
#ifdef DBG_MESSAGES
				Serial.print("\n\t ### Send the GET request (GET /time.php HTTP/1.1\nHost: shredcat.zxq.net\n\n) -> going to HTTP_TRANSFER");
#endif
		    		Xport.print("GET /my_php/time.php HTTP/1.1\nHost: shredcat.zxq.net\n\n");
				HttpStatus = HTTP_TRANSFER;
			}else{
				HttpStatus = HTTP_IDLE;
			}
		}
		break;
	case HTTP_TRANSFER:
		if(Xport.available()){
			input = (char)Xport.read();
                        switch(input){
                        case '[':
				// Found start of string
				string_start = 1;
#ifdef DBG_MESSAGES
//				Serial.print("\n\t ### Got < char -> start logging");
#endif
                                break;
                        case ']':
				HttpStatus = HTTP_DISCONNECTED;
				string_start = 0;
#ifdef DBG_MESSAGES
//				Serial.print("\n\t ### Got > char -> stop logging and going to HTTP_DISCONNECTED");
#endif
				break;
			default:
				if(string_start){
					ReturnStr[ReturnStrCounter++] = input;
					if(ReturnStrCounter == 256){
						HttpStatus = HTTP_DISCONNECTED;
						string_start = 0;
					}
				}
                                break;
			}
		}
		break;
	case HTTP_DISCONNECTED:
                Xport.flush(); 
		// Print the string:
		Serial.print("\n --> Answer from server: ");
		for(int i=0;i<ReturnStrCounter;i++){
			Serial.print((char)ReturnStr[i]);
		}

		// Read every remaining data from Xport
		while(Xport.available()){
			input = Xport.read();
		}
                Xport.print('D');
                Xport.flush(); 
                

		// Reset everyting:
#ifdef DBG_MESSAGES
		Serial.print("\n\t ### Printed return string, cleared Xport buffer and reset of string and counter -> going to HTTP_IDLE");
#endif
		printMenu();
		HttpStatus = HTTP_IDLE;
		ReturnStrCounter = 0;
		string_start = 0;
		break;
	case HTTP_ERROR:
		Serial.print("\n\n ==> HTTP ERROR");
		break;
	}

}


void printMenu(){
	Serial.print("\n");
	Serial.print("\n");
	Serial.print("Menu for Arduino server:\n");
	Serial.print("========================\n");
	Serial.print("t\tGet time from server\n");
	Serial.print("x\tTBD\n");
	Serial.print("\n");
	Serial.print("Your choice: ?");
}


